/* Copyright (c) 2010, Peter Lényi */
/* Licensed under The BSD License. */

package gem.apps.fs.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Filter class UTF8Filter sets character encoding of every connection to UTF-8
 * if different and forwards connections to wherever they were headed.
 *
 * @author Peter Lényi
 * @version 20100426F
 */
public class UTF8Filter implements Filter
{
    private static final String ENCODING = "UTF-8";

    public UTF8Filter() {} 

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding(ENCODING);
        }
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }

    /**
     * Destroy method for this filter.
     */
    public void destroy() {}

    /**
     * Init method for this filter.
     * @param filterConfig
     *          thrown away.
     */
    public void init(FilterConfig filterConfig) {}
}
